package com.zzb.framework.query.sqlbuilder;

import com.zzb.framework.query.QueryException;
import org.apache.commons.lang3.StringUtils;

/**
 * Created by zhangzhenbin on 18-1-17.
 */
public class CountSqlBuilder {
    final static String SELECT = "select ";
    final static String FROM = " from ";
    final static String COUNT_1_ = " count(1) ";
    public static String getCountSql(String querySql) throws QueryException {
        if (querySql == null || querySql.length() == 0)
            throw new QueryException("查询sql为空，请检查查询sql传入值");
        //去除前方空格
        querySql = StringUtils.removeStart(querySql.toLowerCase()," ");
        StringBuilder querySqlBuilder = new StringBuilder(querySql);
        //判断是否是select语句
        if (querySqlBuilder.indexOf(SELECT) != 0)
            throw new QueryException("查询sql异常，请检查查询sql传入值");
        int indexOfFrom = querySqlBuilder.indexOf(FROM);
        if (indexOfFrom == -1)
            throw new QueryException("查询sql异常，请检查查询sql传入值");
        return querySqlBuilder.delete(SELECT.length(), indexOfFrom).insert(SELECT.length(), COUNT_1_).toString();
    }
}
